package com.yuwen.yuwenRPC.proxy;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @ClassNameMockServiceProxy
 * @Description TODO
 * @Author钰玟
 * @Date2025/3/30 下午4:04
 * @Version 1.0
 **/

/**
 * mock服务代理 (动态代理)
 */
@Slf4j
public class MockServiceProxy  implements InvocationHandler {

    /**
     *
     * @param proxy the proxy instance that the method was invoked on
     *
     * @param method the {@code Method} instance corresponding to
     * the interface method invoked on the proxy instance.  The declaring
     * class of the {@code Method} object will be the interface that
     * the method was declared in, which may be a superinterface of the
     * proxy interface that the proxy class inherits the method through.
     *
     * @param args an array of objects containing the values of the
     * arguments passed in the method invocation on the proxy instance,
     * or {@code null} if interface method takes no arguments.
     * Arguments of primitive types are wrapped in instances of the
     * appropriate primitive wrapper class, such as
     * {@code java.lang.Integer} or {@code java.lang.Boolean}.
     *
     * @return 返回值
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //1. 获取方法返回值类型
        Class<?> returnType = method.getReturnType();
        //2. 得到方法名 ，打印日志
        String methodName = method.getName();
        log.info("mock invoke :{}",methodName);
        //3. 使用mock返回对应类型的返回值
        return getDefaultObject(returnType);
    }

    /**
     * mock方法 返回的默认值
     * @param returnType
     * @return
     */
    private Object getDefaultObject(Class<?> returnType) {
        //1. 判断类型
        //1.1 基本类型
        if (returnType.isPrimitive()) {
            if(returnType == int.class){
                return 0;
            }
            else if(returnType == long.class){
                return 0L;
            }
            else if(returnType == boolean.class){
                return false;
            }
            else if(returnType == double.class){
                return 0.0;
            }
            else if(returnType == float.class){
                return 0.0f;
            }
            else if(returnType == char.class){
                return '\0';
            }
            else if(returnType == short.class){
                return 0;
            }
            else if(returnType == byte.class){
                return 0;
            }
        }
        //2.1 引用类型
            return null;
    }
}
